package cn.tedu.csmall.product.service.impl;

import cn.tedu.csmall.product.ex.ServiceException;
import cn.tedu.csmall.product.mapper.CategoryMapper;
import cn.tedu.csmall.product.pojo.dto.BrandAddNewDTO;
import cn.tedu.csmall.product.pojo.dto.CategoryAddNewDTO;
import cn.tedu.csmall.product.pojo.entity.Category;
import cn.tedu.csmall.product.pojo.vo.CategoryStandardVO;
import cn.tedu.csmall.product.service.ICategoryService;
import cn.tedu.csmall.product.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class CategoryServiceImpl implements ICategoryService {
    @Autowired
    CategoryMapper categoryMapper;

    public CategoryServiceImpl(){
        System.out.println("创建业务实现类: CategoryServiceImpl");
    }


    @Override
    public void addNew(CategoryAddNewDTO categoryAddNewDTO) {
        String name = categoryAddNewDTO.getName();
        int count = categoryMapper.countByName(name);
        if(count != 0){
            throw new ServiceException(ServiceCode.ERR_CONFLICT,"添加类别失败,尝试访问的类别名称不存在!");
        }
        Category category = new Category();
        BeanUtils.copyProperties(categoryAddNewDTO,category);
        categoryMapper.insert(category);
    }

    @Override
    public void delete(Long id) {
        log.debug("开始处理[删除类别数据]的业务,参数:{}",id);
        // 调用Mapper对象的getStandardById()方法执行查询
        CategoryStandardVO queryResult = categoryMapper.getStandardById(id);
        // 判断查询结果是否为null
        if(queryResult == null){
            //是: 无此id对应的数据,抛出异常
            String message = "删除类别数据失败,尝试访问的数据不存在!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        // 调用Mapper对象的deleteById()方法执行删除
        log.debug("即将删除类别数据....");
        categoryMapper.deleteById(id);
        log.debug("删除类别数据完成!");
    }
}
